<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>

    <title>websocket demo</title>

    <meta charset="UTF-8">


    <script type="text/javascript" th:src="@{/js/jquery-3.3.1.min.js}"></script>
    <script type="text/javascript" th:src="@{/js/stomp.js}"></script>
    <script type="text/javascript" th:src="@{/js/sockjs.js}"></script>

</head>
<body onload="disconnect()">
<div style="padding: 0">
    <noscript><h2 style="color: #e80b0a;">Sorry，浏览器不支持WebSocket</h2></noscript>
    <div>

        <div>
            <label style="color: black">输入一个昵称</label>
            <br>
            <input type="text" id="nameInput">
        </div>
        <div>
            <button id="connect" onclick="connect();">连接</button>
            <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
        </div>
        <br>

        <div>
            <button id="createGame" onclick="createGame();">创建游戏</button>
            <br>
            <input id="joinGame" placeholder="输入游戏id加入游戏">
            <button onclick="joinGame();">加入游戏</button>

        </div>

        <br>
        <div id="conversationDiv">
            <label style="color: black">个人消息显示区域</label>
            <p id="response-for-one" style="color: black"></p>

            <label style="color: black">所有消息显示区域</label>
            <p id="response-for-all" style="color: black"></p>

            <br>
            <br>
            <br>
            <br>
            <input type="text" id="name"/>
            <button id="sendName" onclick="sendName();">发送</button>
            <p id="response" style="color: black"></p>
        </div>
    </div>

</div>

<script type="text/javascript">
    // var sock = new SockJS("http://127.0.0.1:8080/chat");//连接endpoint名为"endpointChat"的endpoint

    // var stompClient = Stomp.over(sock);

    var webSocket = null;

    function setConnected(connected) {
        // document.getElementById("connect").disabled = connected;
        // document.getElementById("disconnect").disabled = !connected;
        // document.getElementById("conversationDiv").style.visibility = connected ? 'visible' : 'hidden';
//        $("#connect").disabled = connected;
//        $("#disconnect").disabled = !connected;
//         $("#response").html();
    }

    function connect() {
        // var socket = new SockJS('http://localhost:8080/mnpanonymousservice/ws');
        // var socket = new WebSocket('ws://127.0.0.1:8080/mnpanonymousservice/demo');
        // stompClient = Stomp.over(socket);
        // stompClient.connect({}, function (frame) {
        //     setConnected(true);
        //     console.log('Connected:' + frame);
        //     stompClient.subscribe('/topic/say', function (response) {
        //         showResponse(JSON.parse(response.body).content);
        //     })
        // });

        // stompClient.connect('guest', 'guest', function (frame) {
        //     //订阅/user/queue/notifications发送的消息,这里与在simpMessagingTemplate.convertAndSendToUser定义地址一致,/user是必须的
        //     stompClient.subscribe("/user/queue/notifications", handleNotification);
        // });
        webSocket = new WebSocket("ws://127.0.0.1:8080/ws/" + $("#nameInput").val());

        // webSocket = new WebSocket("ws://localhost:9030/websocket/"+document.getElementById('username').value);
        webSocket.onmessage = function (evt) {
            var received_msg = evt.data;
            console.log(received_msg);
            handleNotification(JSON.parse(received_msg));
        };
    }

    function createGame() {
        // var message = {
        //     "type": 1,
        //     "sourceUser": $("#nameInput").val(),
        //     "gameMessage": {
        //         "type": 1
        //     }
        // };

        let message = {
            "type": 1,
            "sourceUser": $("#nameInput").val(),
            "gameMessage": {
                "type": 202
            }
        };
        webSocket.send(JSON.stringify(message));
    }

    function joinGame() {

        // var message = {
        //     "sourceUser": $("#nameInput").val(),
        //     "type": 0,
        //     "content": $("#joinGame").val(),
        //     "gameMessage": {
        //         "type": 2
        //     }
        // };
        // webSocket.send(JSON.stringify(message));

        let message = {
            "type": 2,
            "sourceUser": $("#nameInput").val(),
            "gameMessage": {
                "type": 202
            }
        };
        webSocket.send(JSON.stringify(message));
    }


    function handleNotification(msgObj) {
        var type = msgObj.type;
        console.log(msgObj);
        switch (type) {
            case 0:
                showMessage(msgObj.content, true);
                break;
            case 1:
                showMessage(msgObj.content, false);
                break;
            case 2:
                var gameModel = msgObj.data;
                var rounds = gameModel.rounds;
                console.log(rounds);

                let i = 1;
                for (let key in rounds) {
                    let queObj = rounds[key];
                    console.log(queObj);
                    setTimeout(function () {
                        showMessage(queObj.question.question, true);
                        showMessage(queObj.question.answerA, true);
                        showMessage(queObj.question.answerB, true);
                        showMessage(queObj.question.answerC, true);
                        showMessage(queObj.question.answerD, true);
                    }, 1000 * i);
                    i++;
                }
                // for (var i = 0; i < rounds.length; i++) {
                //     console.log("11111");
                //     console.log();
                //     setTimeout(function () {
                //         showMessage(rounds["(i+1).toString() "].question, true);
                //     }, 5000 * (i + 1));
                //     // showMessage()
                // }
                break;
            default:
                break;

        }

    }

    function showMessage(message, toOne) {
        if (toOne) {
            var $rsp1 = $("#response-for-one");
            var oriMsg1 = $rsp1.html();
            $rsp1.html(oriMsg1 + "<br>" + message);
        } else {
            var $rsp2 = $("#response-for-all");
            var oriMsg2 = $rsp2.html();
            $rsp2.html(oriMsg2 + "<br>" + message);
        }

    }

    function disconnect() {
        if (webSocket != null) {
            webSocket.disconnect();
        }
    }

    function sendName() {
        var name = $('#name').val();
        // var split = name.split(" ");
        var message = {
            "type": name,
        };
        webSocket.send(JSON.stringify(message));
        // $("#text").val("");
        // console.log('name:' + name);
        // stompClient.send("/welcome", {}, JSON.stringify({'content': name}));
    }

    function sendSpittle() {
        var name = $('#name').val();
        console.log('name:' + name);
        stompClient.send("/chat", {}, JSON.stringify({'content': name}));
    }

    function showResponse(message) {
        $("#response").html(message);
    }
</script>
</body>
</html>